package com.itheima.utils;

/**
 * 接口限流
 */
public class CounterDemo {
	/**
	 * 当前系统时间毫秒值
	 */
	private long timeStamp = getNowTime();//12
	/**
	 * 请求数量，默认值为0
	 */
	private int requestCount = 0;
	/**
	 * 1秒内最大请求数
	 */
	private final int limit = 100;
	/**
	 * 1秒内【时间窗口】
	 */
	private final long interval = 1000;   // 1000毫秒 1秒

	/**
	 * 获取当前系统时间
	 * 
	 * @return long
	 */
	public long getNowTime() {
		return System.currentTimeMillis();
	}

	public boolean grant() {
		long now = getNowTime();
		if (now < timeStamp + interval) {
			// 在时间窗口
			requestCount++;
			// 判断当前时间窗口内是否超时过最大球球控制数
			return requestCount <= limit;
		} else {
			timeStamp = now;
			// 超时重置
			requestCount = 1;
			return true;
		}

	}
	
	public static void main(String[] args) {
		CounterDemo counterDemo = new CounterDemo();
		for (int i = 0; i < 101; i++) {
			boolean grant = counterDemo.grant();
			System.out.println("第"+i+"次接口调用：" + (grant?"成功":"失败"));
		}
		
	}

}